<template>
  <div class="login-container">
    <van-nav-bar
      title="登录"
      class="page-nav-bar"
      left-arrow
      @click-left="$router.back()"
    />
    <!-- 登录表单 -->
    <van-form
      ref="loginForm"
      @submit="onSubmit"
      :show-error="false"
      :show-error-message="false"
      @failed="onFailed"
      :validate-first="true"
    >
      <van-field
        name="mobile"
        v-model="user.mobile"
        icon-prefix="toutiao"
        left-icon="shouji"
        placeholder="请输入手机号"
        :rules="userFormRules.mobile"
        type="number"
        maxlength="11"
        center
      />
      <van-field
        name="code"
        v-model="user.code"
        clearable
        icon-prefix="toutiao"
        left-icon="yanzhengma"
        placeholder="请输入验证码"
        :rules="userFormRules.code"
        maxlength="6"
        center
      >
        <template #button>
          <van-count-down
            v-if="isCountDownShow"
            :time="1000 * 60"
            format="ss s"
            @finish="isCountDownShow = false"
          />
          <van-button
            v-else
            class="send-btn"
            native-type="button"
            size="mini"
            @click.prevent="onSendSms"
            round
            :loding="isSendSmsLoding"
            >发送验证码</van-button
          >
        </template>
      </van-field>

      <div class="login-btn-wrap">
        <van-button class="login-btn" type="info" block>登录</van-button>
      </div>
      <!-- /登录表单 -->
    </van-form>
  </div>
</template>

<script>
import { login, sendSms } from "../api/user.js";
export default {
  name: "login",
  data() {
    return {
      user: {
        mobile: "13911111111",
        code: "246810"
      },
      userFormRules: {
        mobile: [
          { required: true, message: "手机号不能为空" },
          {
            pattern: /^[1][3,5,7,8][0-9]{9}$/,
            message: "手机号格式错误"
          }
        ],
        code: [
          { required: true, message: "验证码不能为空" },
          {
            pattern: /^\d{6}$/,
            message: "验证码格式错误"
          }
        ]
      },
      // 倒计时的状态
      isCountDownShow: false,
      // 发送验证码的状态的按钮
      isSendSmsLoding: false
    };
  },
  methods: {
    async onSubmit() {
      this.$toast.loading({
        duration: 2000,
        forbidClick: true,
        message: "登陆中·····"
      });
      try {
        const { data: res } = await login(this.user);
        console.log(res);
        
        this.$toast.success("登陆成功");
        this.$store.commit("setUser", res.data);

        // 清除layout的缓存，让它重新渲染
        this.$store.commit('removeCachePage','layout')

        // 登陆成功跳转回原来的界面
        // this.$router.back()
        this.$router.push(this.$route.query.redirect || '/')
      } catch (err) {
        if (err.response.status === 400) {
          console.log(err);
          this.$toast.fail("登陆失败,手机号或验证码错误");
        }
      }
    },
    async onSendSms() {
      try {
        await this.$refs.loginForm.validate("mobile");

        // 验证码发送
        this.isSendSmsLoding = true;

        await sendSms(this.user.mobile);

        // 显示倒计时
        this.isCountDownShow = true;
      } catch (err) {
        // 不同的错误要有不同的判断
        let message = "";
        if (err && err.response && err.response.status === 429) {
          // 发送短信失败的错误
          message = "发送太频繁了，请稍后重试";
        } else if ((err.name = "mobile")) {
          // 表单验证失败的错误
          message = err.message;
        } else {
          // 发送失败，请稍后重试
          message = "发送失败，请稍候重试";
        }
        this.$toast({
          message: messgae,
          position: "top"
        });
      }
      // 成功与否关闭loding状态
      this.isSendSmsLoding = false;
    },
    // 验证形式通过弹窗形式
    onFailed(error) {
      if (error.errors[0]) {
        this.$toast({
          message: error.errors[0].message,
          position: "top"
        });
      }
    }
  }
};
</script>
<style scoped lang="less">
.login-container {
  .send-btn {
    width: 76px;
    height: 23px;
    background-color: #ededed;
    .van-button_text {
      font-size: 11px;
      color: #666;
    }
  }
  .login-btn-wrap {
    padding: 26px 16px;
    .login-btn {
      background-color: #6db4fb;
      border: none;
      .van-botton__text {
        font-size: 15px;
      }
    }
  }
}
</style>
